import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:permission_handler/permission_handler.dart' as permission_handler;

/// 权限管理服务
/// 
/// 提供统一的权限申请、检查和管理功能
/// 支持Android和iOS平台的各种系统权限
class PermissionService extends GetxService {
  /// 权限服务标签
  static const String tag = 'PermissionService';
  
  // 权限申请结果统计
  final Map<Permission, PermissionStatus> _permissionResults = {};
  
  /// 初始化权限服务
  @override
  void onInit() {
    super.onInit();
    debugPrint('$tag: 权限服务初始化');
  }

  /// 检查单个权限状态
  /// 
  /// [permission] 要检查的权限
  /// 返回权限状态
  Future<PermissionStatus> checkPermission(Permission permission) async {
    try {
      final status = await permission.status;
      debugPrint('$tag: 检查权限 ${permission.toString()} - 状态: $status');
      return status;
    } catch (e) {
      debugPrint('$tag: 检查权限失败 - ${permission.toString()}: $e');
      return PermissionStatus.denied;
    }
  }

  /// 申请单个权限
  /// 
  /// [permission] 要申请的权限
  /// [showRationale] 是否显示权限说明对话框
  /// [autoShowSettings] 权限被永久拒绝时，是否自动显示设置引导弹框（默认true）
  /// 返回权限申请结果
  Future<PermissionRequestResult> requestPermission(
    Permission permission, {
    bool showRationale = true,
    bool autoShowSettings = true,
  }) async {
    try {
      debugPrint('$tag: 开始申请权限 - ${permission.toString()}');
      
      // 检查当前权限状态
      final currentStatus = await permission.status;
      debugPrint('$tag: 当前权限状态 - $currentStatus');
      
      // 如果已经授权，直接返回
      if (_isPermissionGranted(currentStatus)) {
        debugPrint('$tag: 权限已授权，无需申请');
        return PermissionRequestResult(
          permission: permission,
          status: currentStatus,
          isGranted: true,
          message: _getPermissionStatusMessage(currentStatus),
        );
      }
      
      // 🎯 关键修复：如果权限被永久拒绝，自动引导用户到设置页面
      if (currentStatus == PermissionStatus.permanentlyDenied && autoShowSettings) {
        debugPrint('$tag: 权限被永久拒绝，自动显示设置引导弹框');
        return await _handlePermissionDenied(permission, isPermanent: true);
      }
      
      // 🔥 如果需要显示权限说明，同时显示顶部提示和系统权限请求
      if (showRationale && currentStatus == PermissionStatus.denied) {
        debugPrint('$tag: 显示顶部权限说明提示（非阻塞）');
        
        // 🔥 显示顶部提示框（非阻塞，不等待用户确认）
        _showTopPermissionHint(permission);
        
        // 🔥 短暂延迟，让提示框先显示出来
        await Future.delayed(const Duration(milliseconds: 100));
      }
      
      // 申请权限（会显示系统原生权限请求）
      debugPrint('$tag: 开始调用系统权限请求');
      final status = await permission.request();
      
      // 🔥 关闭顶部提示框
      if (showRationale && currentStatus == PermissionStatus.denied) {
        Get.closeAllSnackbars();
      }
      _permissionResults[permission] = status;
      
      debugPrint('$tag: 权限申请结果 - ${permission.toString()}: $status');
      
          // 🎯 关键优化：申请后如果被拒绝（denied或permanentlyDenied），引导用户到设置
      if (!_isPermissionGranted(status) && autoShowSettings) {
        if (status == PermissionStatus.permanentlyDenied) {
          debugPrint('$tag: 权限被永久拒绝，显示设置引导弹框');
          return await _handlePermissionDenied(permission, isPermanent: true);
        } else if (status == PermissionStatus.denied) {
          debugPrint('$tag: 权限被拒绝，显示设置引导弹框');
          return await _handlePermissionDenied(permission, isPermanent: false);
        }
      }
      
      return PermissionRequestResult(
        permission: permission,
        status: status,
        isGranted: _isPermissionGranted(status),
        message: _getPermissionStatusMessage(status),
      );
      
    } catch (e) {
      debugPrint('$tag: 权限申请异常 - ${permission.toString()}: $e');
      return PermissionRequestResult(
        permission: permission,
        status: PermissionStatus.denied,
        isGranted: false,
        message: '权限申请失败: ${e.toString()}',
      );
    }
  }

  /// 批量申请权限
  /// 
  /// [permissions] 要申请的权限列表
  /// [showRationale] 是否显示权限说明对话框
  /// 返回权限申请结果列表
  Future<List<PermissionRequestResult>> requestPermissions(
    List<Permission> permissions, {
    bool showRationale = true,
  }) async {
    debugPrint('$tag: 开始批量申请权限 - 共${permissions.length}个');
    
    final results = <PermissionRequestResult>[];
    
    for (final permission in permissions) {
      final result = await requestPermission(permission, showRationale: showRationale);
      results.add(result);
      
      // 如果用户拒绝了某个权限，询问是否继续申请其他权限
      if (!result.isGranted && showRationale) {
        final shouldContinue = await _askContinueRequest(permission, permissions.length - results.length);
        if (!shouldContinue) {
          debugPrint('$tag: 用户选择停止申请剩余权限');
          break;
        }
      }
    }
    
    debugPrint('$tag: 批量权限申请完成 - 成功: ${results.where((r) => r.isGranted).length}/${results.length}');
    return results;
  }

  /// 检查多个权限状态
  /// 
  /// [permissions] 要检查的权限列表
  /// 返回权限状态映射
  Future<Map<Permission, PermissionStatus>> checkPermissions(
    List<Permission> permissions,
  ) async {
    debugPrint('$tag: 批量检查权限状态 - 共${permissions.length}个');
    
    final results = <Permission, PermissionStatus>{};
    
    for (final permission in permissions) {
      final status = await checkPermission(permission);
      results[permission] = status;
    }
    
    return results;
  }

  /// 打开应用设置页面
  /// 
  /// 用于用户手动开启被永久拒绝的权限
  Future<bool> openAppSettings() async {
    try {
      debugPrint('$tag: 打开应用设置页面');
      final result = await permission_handler.openAppSettings();
      debugPrint('$tag: 打开设置页面结果: $result');
      return result;
    } catch (e) {
      debugPrint('$tag: 打开设置页面失败: $e');
      return false;
    }
  }

  /// 获取所有已申请权限的统计信息
  Map<PermissionStatus, List<Permission>> getPermissionStats() {
    final stats = <PermissionStatus, List<Permission>>{
      PermissionStatus.granted: [],
      PermissionStatus.denied: [],
      PermissionStatus.permanentlyDenied: [],
      PermissionStatus.restricted: [],
      PermissionStatus.limited: [], // 添加limited状态统计
    };
    
    _permissionResults.forEach((permission, status) {
      stats[status]?.add(permission);
    });
    
    return stats;
  }

  /// 获取权限详细说明
  /// 
  /// 特别针对limited状态提供详细解释
  /// [permission] 权限类型
  /// [status] 权限状态
  /// 返回详细说明文本
  String getPermissionDetailedDescription(Permission permission, PermissionStatus status) {
    if (status == PermissionStatus.limited && permission == Permission.photos) {
      return '📸 iOS相册权限说明：\n\n'
             '✅ 当前状态：部分权限（可正常使用）\n'
             '📱 这意味着：\n'
             '  • 您选择了"选择照片"而非"允许访问所有照片"\n'
             '  • App只能访问您主动选择的照片\n'
             '  • 这是iOS 14+的隐私保护功能\n'
             '  • 您可以随时在相册中添加或移除可访问的照片\n\n'
             '🔧 如需访问全部照片：\n'
             '  设置 → 隐私与安全性 → 照片 → 选择"完全访问权限"';
    }
    
    return _getPermissionDescription(permission);
  }

  /// 清除权限申请历史
  void clearPermissionHistory() {
    debugPrint('$tag: 清除权限申请历史');
    _permissionResults.clear();
  }

  // ==================== 专用权限申请方法 ====================

  /// 申请相册/照片权限
  /// 
  /// 自动处理不同平台的权限差异和fallback策略
  /// Android: photos -> storage (fallback)
  /// iOS: photos
  /// 
  /// [showRationale] 是否显示权限说明对话框
  /// 返回权限申请结果
  Future<PermissionRequestResult> requestGalleryPermission({
    bool showRationale = true,
  }) async {
    try {
      debugPrint('$tag: 开始申请相册权限');
      
      if (Platform.isAndroid) {
        // Android 平台：先检查是否已有任何可用的权限
        final photosStatus = await Permission.photos.status;
        final storageStatus = await Permission.storage.status;
        
        debugPrint('$tag: Android平台权限状态检查 - photos: $photosStatus, storage: $storageStatus');
        
        // 如果photos权限可用（granted或limited），直接返回成功
        if (_isPermissionGranted(photosStatus)) {
          debugPrint('$tag: Android photos权限已可用，无需申请');
          return PermissionRequestResult(
            permission: Permission.photos,
            status: photosStatus,
            isGranted: true,
            message: _getPermissionStatusMessage(photosStatus),
          );
        }
        
        // 如果storage权限可用，直接返回成功
        if (_isPermissionGranted(storageStatus)) {
          debugPrint('$tag: Android storage权限已可用，无需申请');
          return PermissionRequestResult(
            permission: Permission.photos, // 统一返回photos权限类型
            status: PermissionStatus.granted,
            isGranted: true,
            message: '相册权限已授权（通过storage权限）',
          );
        }
        
        // 都没有权限时，优先申请photos权限
        debugPrint('$tag: Android平台 - 申请photos权限');
        final photosResult = await requestPermission(Permission.photos, showRationale: showRationale);
        
        if (photosResult.isGranted) {
          debugPrint('$tag: Android photos权限申请成功 (状态: ${photosResult.status})');
          return photosResult;
        }
        
        // 如果photos权限被永久拒绝，直接返回失败，不再尝试storage
        if (photosResult.status == PermissionStatus.permanentlyDenied) {
          debugPrint('$tag: photos权限被永久拒绝，不再尝试storage权限');
          return photosResult;
        }
        
        // 只有在photos权限被普通拒绝时，才尝试storage权限（避免双重弹窗）
        if (photosResult.status == PermissionStatus.denied && showRationale) {
          debugPrint('$tag: Android photos权限被拒绝，尝试storage权限作为fallback');
          final storageResult = await requestPermission(Permission.storage, showRationale: false); // 关闭storage的说明弹窗
          
          if (storageResult.isGranted) {
            debugPrint('$tag: Android storage权限申请成功（fallback）');
            return PermissionRequestResult(
              permission: Permission.photos, // 统一返回photos权限类型
              status: PermissionStatus.granted,
              isGranted: true,
              message: '相册权限已授权（通过storage权限）',
            );
          } 
        }
        
        // 权限申请失败
        debugPrint('$tag: Android相册权限申请失败');
        return PermissionRequestResult(
          permission: Permission.photos,
          status: photosResult.status,
          isGranted: false,
          message: '相册权限被拒绝，无法选择照片',
        );
        
      } else if (Platform.isIOS) {
        // iOS 平台：直接申请photos权限
        debugPrint('$tag: iOS平台 - 申请photos权限');
        final iosResult = await requestPermission(Permission.photos, showRationale: showRationale);
        
        debugPrint('$tag: iOS photos权限申请结果: ${iosResult.isGranted}');
        return iosResult;
        
      } else {
        // 其他平台（如Web、Windows等）
        debugPrint('$tag: 其他平台 - 尝试申请photos权限');
        return await requestPermission(Permission.photos, showRationale: showRationale);
      }
      
    } catch (e) {
      debugPrint('$tag: 相册权限申请异常: $e');
      return PermissionRequestResult(
        permission: Permission.photos,
        status: PermissionStatus.denied,
        isGranted: false,
        message: '相册权限申请异常: ${e.toString()}',
      );
    }
  }

  /// 申请相机权限
  /// 
  /// 统一处理相机权限申请
  /// [showRationale] 是否显示权限说明对话框
  /// 返回权限申请结果
  Future<PermissionRequestResult> requestCameraPermission({
    bool showRationale = true,
  }) async {
    debugPrint('$tag: 申请相机权限');
    return await requestPermission(Permission.camera, showRationale: showRationale);
  }

  /// 申请位置权限
  /// 
  /// 统一处理位置权限申请
  /// [showRationale] 是否显示权限说明对话框
  /// 返回权限申请结果
  Future<PermissionRequestResult> requestLocationPermission({
    bool showRationale = true,
  }) async {
    debugPrint('$tag: 申请位置权限');
    return await requestPermission(Permission.location, showRationale: showRationale);
  }
  
  /// 检查位置权限是否已授予
  bool get isLocationPermissionGranted {
    // 这是同步方法，只能返回缓存的结果
    // 实际使用时应该先调用 checkPermission(Permission.location)
    return _permissionResults[Permission.location]?.isGranted ?? false;
  }

  /// 申请媒体权限组（相机 + 相册）
  /// 
  /// 同时申请相机和相册权限，适用于图片选择场景
  /// [showRationale] 是否显示权限说明对话框
  /// 返回权限申请结果列表
  Future<MediaPermissionResult> requestMediaPermissions({
    bool showRationale = true,
  }) async {
    debugPrint('$tag: 开始申请媒体权限组（相机+相册）');
    
    try {
      // 申请相机权限
      final cameraResult = await requestCameraPermission(showRationale: showRationale);
      
      // 申请相册权限
      final galleryResult = await requestGalleryPermission(showRationale: showRationale);
      
      final hasAllPermissions = cameraResult.isGranted && galleryResult.isGranted;
      
      debugPrint('$tag: 媒体权限申请完成 - 相机: ${cameraResult.isGranted}, 相册: ${galleryResult.isGranted}');
      
      return MediaPermissionResult(
        cameraResult: cameraResult,
        galleryResult: galleryResult,
        hasAllPermissions: hasAllPermissions,
      );
      
    } catch (e) {
      debugPrint('$tag: 媒体权限申请异常: $e');
      
      final errorResult = PermissionRequestResult(
        permission: Permission.camera,
        status: PermissionStatus.denied,
        isGranted: false,
        message: '媒体权限申请异常: ${e.toString()}',
      );
      
      return MediaPermissionResult(
        cameraResult: errorResult,
        galleryResult: errorResult,
        hasAllPermissions: false,
      );
    }
  }

  // ==================== 私有方法 ====================

  /// 判断权限是否可用
  /// 
  /// 对于不同权限类型有不同的判断标准：
  /// - photos权限：granted 或 limited 都可以使用
  /// - 其他权限：只有granted才可以使用
  bool _isPermissionGranted(PermissionStatus status) {
    switch (status) {
      case PermissionStatus.granted:
        return true;
      case PermissionStatus.limited:
        // limited状态对于photos权限是可用的（部分权限）
        return true;
      case PermissionStatus.denied:
      case PermissionStatus.permanentlyDenied:
      case PermissionStatus.restricted:
      case PermissionStatus.provisional:
        return false;
    }
  }

  // 私有方法：处理被拒绝的权限
  /// [isPermanent] 是否为永久拒绝
  Future<PermissionRequestResult> _handlePermissionDenied(
    Permission permission, {
    required bool isPermanent,
  }) async {
    final shouldOpenSettings = await Get.dialog<bool>(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        child: Container(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 图标
              Container(
                width: 64,
                height: 64,
                decoration: BoxDecoration(
                  color: const Color(0xFFFF9800).withOpacity(0.1),
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.settings,
                  size: 32,
                  color: Color(0xFFFF9800),
                ),
              ),
              
              const SizedBox(height: 20),
              
              // 标题
              Text(
                isPermanent 
                    ? '需要开启${_getPermissionDisplayName(permission)}权限'
                    : '${_getPermissionDisplayName(permission)}权限被拒绝',
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
                textAlign: TextAlign.center,
              ),
              
              const SizedBox(height: 12),
              
              // 说明
              Text(
                _getPermissionDescription(permission),
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                  height: 1.5,
                ),
                textAlign: TextAlign.center,
              ),
              
              const SizedBox(height: 8),
              
              // 操作步骤
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.blue[50],
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      isPermanent ? '操作步骤：' : '如需使用此功能：',
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w600,
                        color: Colors.blue[900],
                      ),
                    ),
                    const SizedBox(height: 6),
                    _buildStep('1', '点击"前往设置"按钮'),
                    _buildStep('2', '找到"权限管理"'),
                    _buildStep('3', '开启${_getPermissionDisplayName(permission)}权限'),
                  ],
                ),
              ),
              
              const SizedBox(height: 24),
              
              // 按钮
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      onPressed: () => Get.back(result: false),
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                          side: BorderSide(color: Colors.grey[300]!),
                        ),
                      ),
                      child: const Text(
                        '取消',
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.grey,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () => Get.back(result: true),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFFE33641),
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        elevation: 0,
                      ),
                      child: const Text(
                        '前往设置',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: true,
    ) ?? false;

    if (shouldOpenSettings) {
      debugPrint('$tag: 用户选择前往设置');
      await permission_handler.openAppSettings();
    } else {
      debugPrint('$tag: 用户取消前往设置');
    }

    return PermissionRequestResult(
      permission: permission,
      status: isPermanent ? PermissionStatus.permanentlyDenied : PermissionStatus.denied,
      isGranted: false,
      message: shouldOpenSettings ? '已引导用户到设置页面' : '用户取消前往设置',
    );
  }
  
  // 构建操作步骤项
  Widget _buildStep(String number, String text) {
    return Padding(
      padding: const EdgeInsets.only(top: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 18,
            height: 18,
            decoration: BoxDecoration(
              color: Colors.blue[100],
              shape: BoxShape.circle,
            ),
            child: Center(
              child: Text(
                number,
                style: TextStyle(
                  fontSize: 11,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue[900],
                ),
              ),
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              text,
              style: TextStyle(
                fontSize: 13,
                color: Colors.grey[700],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 🔥 私有方法：显示顶部权限说明提示（简化版，非阻塞）
  void _showTopPermissionHint(Permission permission) {
    Get.snackbar(
      '',  // 空标题
      '',  // 空消息（使用messageText自定义）
      snackPosition: SnackPosition.TOP,
      backgroundColor: const Color(0xFF2196F3).withOpacity(0.95),
      colorText: Colors.white,
      margin: const EdgeInsets.only(top: 100, left: 20, right: 20),
      borderRadius: 12,
      duration: const Duration(seconds: 10),  // 10秒后自动关闭（或系统权限请求完成时关闭）
      isDismissible: false,
      animationDuration: const Duration(milliseconds: 300),
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      titleText: const SizedBox.shrink(),  // 隐藏标题
      messageText: Row(
        children: [
          // 小图标
          const Icon(
            Icons.info_outline,
            color: Colors.white,
            size: 18,
          ),
          const SizedBox(width: 12),
          // 说明文字
          Expanded(
            child: Text(
              '${_getPermissionDescription(permission)}',
              style: const TextStyle(
                color: Colors.white,
                fontSize: 13,
                height: 1.3,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 私有方法：显示权限申请说明
  Future<bool> _showPermissionRationale(Permission permission) async {
    return await Get.dialog<bool>(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        child: Container(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 图标
              Container(
                width: 64,
                height: 64,
                decoration: BoxDecoration(
                  color: const Color(0xFF2196F3).withOpacity(0.1),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  _getPermissionIcon(permission),
                  size: 32,
                  color: const Color(0xFF2196F3),
                ),
              ),
              
              const SizedBox(height: 20),
              
              // 标题
              Text(
                '需要${_getPermissionDisplayName(permission)}权限',
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
                textAlign: TextAlign.center,
              ),
              
              const SizedBox(height: 12),
              
              // 说明
              Text(
                _getPermissionDescription(permission),
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                  height: 1.5,
                ),
                textAlign: TextAlign.center,
              ),
              
              const SizedBox(height: 8),
              
              // 提示
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.blue[50],
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  '点击"允许"后，系统将请求您授权${_getPermissionDisplayName(permission)}权限',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.blue[900],
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
              
              const SizedBox(height: 24),
              
              // 按钮
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      onPressed: () {
                        debugPrint('$tag: 用户点击了"取消"按钮');
                        Get.back(result: false);
                      },
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                          side: BorderSide(color: Colors.grey[300]!),
                        ),
                      ),
                      child: const Text(
                        '取消',
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.grey,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () {
                        debugPrint('$tag: 用户点击了"允许"按钮');
                        Get.back(result: true);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF2196F3),
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        elevation: 0,
                      ),
                      child: const Text(
                        '允许',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: false,  // 🔥 禁止点击外部关闭，用户必须做出选择
    ) ?? false;
  }
  
  // 获取权限对应的图标
  IconData _getPermissionIcon(Permission permission) {
    switch (permission) {
      case Permission.camera:
        return Icons.camera_alt;
      case Permission.microphone:
        return Icons.mic;
      case Permission.location:
      case Permission.locationAlways:
      case Permission.locationWhenInUse:
        return Icons.location_on;
      case Permission.storage:
      case Permission.photos:
      case Permission.mediaLibrary:
        return Icons.photo_library;
      case Permission.notification:
        return Icons.notifications;
      case Permission.contacts:
        return Icons.contacts;
      case Permission.phone:
        return Icons.phone;
      case Permission.sms:
        return Icons.sms;
      case Permission.calendar:
        return Icons.calendar_today;
      default:
        return Icons.security;
    }
  }

  // 私有方法：询问是否继续申请权限
  Future<bool> _askContinueRequest(Permission rejectedPermission, int remainingCount) async {
    if (remainingCount <= 0) return false;
    
    return await Get.dialog<bool>(
      AlertDialog(
        title: const Text('权限申请'),
        content: Text(
          '${_getPermissionDisplayName(rejectedPermission)}权限被拒绝。\n\n'
          '还有${remainingCount}个权限需要申请，是否继续？',
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('停止申请'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            child: const Text('继续申请'),
          ),
        ],
      ),
    ) ?? false;
  }

  // 私有方法：获取权限显示名称
  String _getPermissionDisplayName(Permission permission) {
    switch (permission) {
      case Permission.camera:
        return '相机';
      case Permission.microphone:
        return '麦克风';
      case Permission.location:
      case Permission.locationAlways:
      case Permission.locationWhenInUse:
        return '位置';
      case Permission.storage:
      case Permission.photos:
      case Permission.mediaLibrary:
        return '存储';
      case Permission.notification:
        return '通知';
      case Permission.contacts:
        return '通讯录';
      case Permission.phone:
        return '电话';
      case Permission.sms:
        return '短信';
      case Permission.sensors:
        return '传感器';
      case Permission.calendar:
        return '日历';
      default:
        return permission.toString().split('.').last;
    }
  }

  // 私有方法：获取权限描述
  String _getPermissionDescription(Permission permission) {
    switch (permission) {
      case Permission.camera:
        return '应用需要访问您的相机，用于拍照和扫码等功能。';
      case Permission.microphone:
        return '应用需要访问您的麦克风，用于录音和语音通话等功能。';
      case Permission.location:
      case Permission.locationAlways:
      case Permission.locationWhenInUse:
        return '应用需要访问您的位置信息，用于提供基于位置的服务。';
      case Permission.storage:
      case Permission.photos:
      case Permission.mediaLibrary:
        return '应用需要访问您的存储空间，用于保存和读取文件。';
      case Permission.notification:
        return '应用需要发送通知的权限，用于及时提醒您重要信息。';
      case Permission.contacts:
        return '应用需要访问您的通讯录，用于联系人相关功能。';
      case Permission.phone:
        return '应用需要访问电话权限，用于拨打电话等功能。';
      case Permission.sms:
        return '应用需要访问短信权限，用于发送验证码等功能。';
      case Permission.sensors:
        return '应用需要访问传感器权限，用于运动检测等功能。';
      case Permission.calendar:
        return '应用需要访问日历权限，用于日程管理等功能。';
      default:
        return '应用需要此权限以正常运行，请允许权限申请。';
    }
  }

  // 私有方法：获取权限状态消息
  String _getPermissionStatusMessage(PermissionStatus status) {
    switch (status) {
      case PermissionStatus.granted:
        return '权限已授权';
      case PermissionStatus.limited:
        return '权限已授权（iOS选择照片模式）'; // 更清晰地说明这是iOS的正常功能
      case PermissionStatus.denied:
        return '权限被拒绝';
      case PermissionStatus.permanentlyDenied:
        return '权限被永久拒绝，需要在设置中手动开启';
      case PermissionStatus.restricted:
        return '权限受限制';
      case PermissionStatus.provisional:
        return '临时权限';
    }
  }
}

/// 权限申请结果
class PermissionRequestResult {
  /// 权限类型
  final Permission permission;
  
  /// 权限状态
  final PermissionStatus status;
  
  /// 是否已授权
  final bool isGranted;
  
  /// 结果消息
  final String message;

  const PermissionRequestResult({
    required this.permission,
    required this.status,
    required this.isGranted,
    required this.message,
  });

  @override
  String toString() {
    return 'PermissionRequestResult{'
        'permission: $permission, '
        'status: $status, '
        'isGranted: $isGranted, '
        'message: $message'
        '}';
  }
}

/// 媒体权限申请结果
/// 
/// 包含相机和相册权限的申请结果
class MediaPermissionResult {
  /// 相机权限申请结果
  final PermissionRequestResult cameraResult;
  
  /// 相册权限申请结果
  final PermissionRequestResult galleryResult;
  
  /// 是否拥有所有权限
  final bool hasAllPermissions;

  const MediaPermissionResult({
    required this.cameraResult,
    required this.galleryResult,
    required this.hasAllPermissions,
  });

  /// 是否拥有相机权限
  bool get hasCameraPermission => cameraResult.isGranted;
  
  /// 是否拥有相册权限
  bool get hasGalleryPermission => galleryResult.isGranted;

  @override
  String toString() {
    return 'MediaPermissionResult{'
        'camera: ${cameraResult.isGranted}, '
        'gallery: ${galleryResult.isGranted}, '
        'hasAll: $hasAllPermissions'
        '}';
  }
}

/// 预定义的权限组
class PermissionGroups {
  /// 基础权限组（相机、相册、位置）
  static const List<Permission> basic = [
    Permission.camera,
    Permission.photos,
    Permission.location,
  ];
  
  /// 媒体权限组（相机、麦克风、相册）
  static const List<Permission> media = [
    Permission.camera,
    Permission.microphone,
    Permission.photos,
  ];
  
  /// 通讯权限组（通讯录、电话、短信）
  static const List<Permission> communication = [
    Permission.contacts,
    Permission.phone,
    Permission.sms,
  ];
  
  /// 全部常用权限
  static const List<Permission> all = [
    Permission.camera,
    Permission.microphone,
    Permission.location,
    Permission.photos,
    Permission.notification,
    Permission.contacts,
    Permission.phone,
  ];
}
